const router = require('koa-router')()
const UserModel = require('../models/user')
const jwt = require('jsonwebtoken');
// const routes=require('../config/congigs')

router.prefix('/api')

//登录
router.post('/login', async (ctx) => {
    ctx.status = 200;

    console.log(ctx.request.body)

    let data = ctx.request.body;
    let {
        username,
        password
    } = data;

    console.log(data, username, password)

    let user = await UserModel.findOne({
        username
    }, {
        routes: 0
    });
    console.log(user);
    if (!user) {
        return ctx.body = {
            code: 400,
            error: '用户不存在'
        }
    }

    if (user.password !== password) {
        return ctx.body = {
            code: 400,
            error: '密码输入错误'
        }
    }
    let users = await UserModel.findOne({
        username
    }, {
        routes: 0,
        password: 0
    });
    console.log(users);
    const token = jwt.sign({
        name: user.username,
        _id: user._id
    }, 'my_token', {
        expiresIn: '2h'
    });


    ctx.body = {
        code: 200,
        token: token,
        reslut: users
    }
})

//注册
router.post('/register', async (ctx) => {
    let data = ctx.request.body
    console.log(data);
    let {
        username,
        password
    } = data;


    let user = await UserModel.findOne({
        username
    });
    console.log(user);
    if (user) {
        return ctx.body = {
            code: 400,
            msg: '用户已注册'
        }
    }

    console.log({
        username,
        password
    })

    let res = await UserModel.create(data);

    ctx.body = {
        code: 200,
        msg: '注册成功',

    };

})

//  修改密码
router.post('/setChangePassword', async (ctx) => {
    let {
        password,
        id
    } = ctx.request.body
    if (!id) {
        ctx.body = {
            code: 400,
            msg: "查询失败"
        }
    }
    let getPassword = ''
    //  await UserModel.findOne({_id:id},function(err,doc){
    //           console.log(111,doc);
    //         if(doc._id==id){
    //            doc.password=password,
    //            console.log("修改成功");
    //            getPassword="修改成功"
    //            doc.save()
    //         }
    //  })
    await UserModel.findByIdAndUpdate({
        _id: id
    }, {
        $set: {
            password: password
        }
    }, {
        new: true
    }, (err, doc) => {
        console.log(doc);
        if (doc._id == id) {
            getPassword = "修改成功"
        }

    });
    ctx.body={
        code:200,
        resoult:getPassword
    }
})

// 获取路由权限
router.post('/getRoutes', async (ctx, next) => {
    let data = ctx.request.body
    console.log(data);
    let {
        root
    } = data
    let res1 = await UserModel.find({
        root
    })
    console.log(res1[0]);
    if (!res1) {
        ctx.body = {
            code: 400,
            msg: '查询失败'
        }
    }
    ctx.body = {
        code: 200,
        msg: '查询成功',
        routes: res1
    }
})

// 获取全部角色人员
router.get("/GetAllRoleData",async(ctx)=>{
    let getuser=await UserModel.find({})
    ctx.body={
        code:200,
        success:getuser
    }
})




//通过昵称查询用户
router.post("/QueryNumberofUsers",async(ctx)=>{
    let {nickname}=ctx.request.body
    if(!nickname){
        ctx.body={
            code:400,
            msg:"参数错误"
        }
    }else{
        let users= await UserModel.findOne({nickname})

        if(!users){
            ctx.body={
                code:400,
                msg:"查询失败"
            }
        }else{
            ctx.body={
                code:200,
                success:users
            }
        }
    }


})

// 设置组织
router.post("/Setuporganization",async(ctx)=>{
    let {id,nickname,department,phone,position}=ctx.request.body
    if(id){
        let setPosition=await UserModel.findByIdAndUpdate({_id:id},{$set:{nickname:nickname,department:department,phone:phone,position:position}})
        if(setPosition){
            ctx.body={
                code:200,
                success:"设置成功"
            }
        }else{
            ctx.body={
                code:200,
                success:"设置失败"
            }
        }
    }else{
        ctx.body={
            code:400,
            msg:"参数错误"
        }
    }


})

//设置角色
router.post("/SettingUpRoles",async(ctx)=>{
    let {id,root}=ctx.request.body
    if(id){
        let userRoot=await UserModel.findByIdAndUpdate({_id:id},{$set:{root:root}})
        if(userRoot){
            ctx.body={
                code:200,
                success:"设置成功"
            }
        }else{
            ctx.body={
                code:400,
                msg:"设置失败"
            }
        }
    }else{
        ctx.body={
            code:400,
            msg:"参数错误，查询失败"
        }
    }
})

// 删除用户
router.post("/DeleteRoleUser",async(ctx)=>{
    res.send('同学，不允许删除')
    // let {id}=ctx.request.body
    // if(id){
    //     let userData=await UserModel.deleteOne({_id:id})
    //     console.log(userData);
    //     if(userData){
    //         ctx.body={
    //             code:200,
    //             success:"删除成功"
    //         }
    //     }else{
    //         ctx.body={
    //             code:400,
    //             msg:"删除失败"
    //         }
    //     }
    // }else{
    //     ctx.body={
    //         code:400,
    //         msg:"参数错误"
    //     }
    // }
})


//测试
router.get('/test',function (ctx,next) {
  ctx.body = {
    msg:"1111111"
  }
})


module.exports = router
